//
//  PlaceHolderTextView.m
//  微博2期
//
//  Created by J on 15/12/7.
//
//

#import "PlaceHolderTextView.h"

@implementation PlaceHolderTextView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        self.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//        self.delegate = self;//不要设置自己的delegate为自己  因为有个delegate属性可以把代理覆盖了
    
        //通知
        //当UITextView的文字发生改变时 自己会发出一个 UITextViewTextDidChangeNotification通知
        [NoficationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];//监听自己发出的通知
//        UIButton * label =[UIButton buttonWithType:UIButtonTypeContactAdd];
//        [self addSubview:label];
        
    
    }
    return self;
    
}

- (void)setPlaceHolder:(NSString *)placeHolder{
    
    _placeHolder = [placeHolder copy];
    [self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor ;
    [self setNeedsDisplay];//会在下一个循环时刻, 调用 drawRect:

}

/**
 *  监听文字改变
 */
- (void)textDidChange{
    [self setNeedsDisplay];//重绘 会自动重新调用 drawRect 方法不要手动调用 重写set方法是为了改变属性之后立即产生效果不重写不会马上发声改变
    //每当调用一次drawRect  就会把之前的东西擦掉
}

//让设置文字的时候调用 drawRect
- (void)setText:(NSString *)text{
    [super setText:text];//先调用父类的方法
    [self setNeedsDisplay];
    
}

//让设置属性文字的时候也调用 drawRect
- (void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
 
    
}

- (void)setFont:(UIFont *)font{
    [super setFont:font];
    [self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect{
    
//    NSLog(@"drawRect");
//    [RamdomColor set];
//    UIRectFill(CGRectMake(20, 20, 20, 20));
    
    if (self.hasText) return;//如果有文字就return 为了不画占位文字
    //每当调用一次drawRect  就会把之前的东西擦掉
        //文字属性
        NSMutableDictionary * atts = [NSMutableDictionary dictionary];
        atts[NSFontAttributeName] = self.font;
    atts[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
        //画文字
//        [self.placeHolder drawAtPoint:CGPointMake(5, 8) withAttributes:atts];
    CGFloat x = 5;
    CGFloat w = rect.size.width-2*x;
    CGFloat y = 8;
    CGFloat h =rect.size.height-2*y;
    [self.placeHolder drawInRect:CGRectMake(x, y, w, h) withAttributes:atts];

}

- (void)dealloc{
  
        
        [NoficationCenter removeObserver:self];

    
}

@end
